package com.huika.dealontop.control.pay.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.GlobalApp;
import com.huika.dealontop.R;
import com.huika.dealontop.config.Constants;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.pay.view.HKWebView;
import com.huika.dealontop.control.pay.view.OnStackBottomListener;
import com.huika.dealontop.support.domain.CouponCodeBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DebugTool;

import java.util.ArrayList;

/**
 * Description:
 * Created by zhouweiyong on 2016/1/12.
 */
public class PaysBuyPayActivity extends BaseAct {

    private HKWebView webView;
    private ProgressBar progressBar;
    private String url;
    private String  payOrderNo;//支付单号

    @Override
    protected void initData() {
        Intent intent = getIntent();
        if (intent!=null){
            url = intent.getStringExtra(Constants.PAYSBUY_URL);
            payOrderNo = intent.getStringExtra(Constants.PAY_PAYMENTORDERID);
        }
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_pay_paysbuy);
    }

    @Override
    protected void initWidget() {
        webView = (HKWebView) findViewById(R.id.wv_paysbuy);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        loadSettings();
        webView.setWebChromeClient(new HkWebChromeClient());

        webView .setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                //http://192.168.18.83:8089/Payment/Success?isDebug=1&paymentOrderId=10724455844
                DebugTool.i("zwy",url);
                if (url.contains("Payment/Success")){
                    Uri uri = Uri.parse(url);
                    String[] query = uri.getQuery().split("&");
                    for (int i = 0;i < query.length;i ++){
                        if (query[i].contains("paymentOrderId")){
                            String paymentOrderId = query[i].split("=")[1];
                            getCouponCode();
                        }
                    }
                }else if(url.contains("Payment/Fail")){
                    showActivity(aty,PayFailActivity.class);
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        webView.setOnBottomListener(new OnStackBottomListener() {
            @Override
            public void onStackBottom() {
                finish();
            }
        });

        webView.loadUrl(url);
    }

    private void getCouponCode(){
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("userId", GlobalApp.getInstance().getUserId());
        ajaxParams.putCommonTypeParam("paymentOrderId", payOrderNo);
        FormResultRequest<ArrayList<CouponCodeBean>> request = new FormResultRequest<ArrayList<CouponCodeBean>>(UrlConstants.PASYSBUYSERVRES, new Response.Listener<RequestResult<ArrayList<CouponCodeBean>>>() {

            @Override
            public void onResponse(RequestResult<ArrayList<CouponCodeBean>> arg0) {
                DebugTool.i("zwy","");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError arg0) {
                DebugTool.i("zwy","");
            }
        },new TypeToken<RequestResult<ArrayList<CouponCodeBean>>>() {}.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }


    public void loadSettings() {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setGeolocationEnabled(true);
        // 保存表单数据
        settings.setSaveFormData( true);
        // 不记住表单密码，不提示记住密码对话框
        settings.setSavePassword( false);

        int minimumFontSize = 1 ;
        settings.setMinimumFontSize(minimumFontSize);
        settings.setMinimumLogicalFontSize(minimumFontSize);

        settings.setUserAgentString("");
        settings.setDisplayZoomControls(false);
        settings.setBuiltInZoomControls(true);
        settings.setSupportMultipleWindows(true);
        settings.setEnableSmoothTransition(true);

        // HTML5 API flags
        settings.setAppCacheEnabled( true);
        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);

        // HTML5 configuration settings.
        settings.setAppCacheMaxSize(6 * 1024 * 1024);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            settings.setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");
            settings.setAppCachePath("/data/data/" + webView.getContext().getPackageName() + "/appcache/");
            settings.setGeolocationDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/geolocation/");
        }else {
            settings.setDatabasePath(this.getDir("databases", Context.MODE_PRIVATE).getPath());
            settings.setAppCachePath(this.getDir("appcache", Context.MODE_PRIVATE).getPath());
            settings.setGeolocationDatabasePath(this .getDir("geolocation", Context.MODE_PRIVATE).getPath());
        }

    }


    class HkWebChromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // 进度条
            progressBar.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
            progressBar.setProgress(newProgress);
            super.onProgressChanged(view, newProgress);

        }

        /**
         * 覆盖默认的window.alert 展示界面，避免 title里显示为“ ：来自file:////”
         */
        public boolean onJsAlert(WebView view, String url, String message,
                                 JsResult result) {
            return super.onJsAlert(view, url, message, result);
        }

        /**
         * 覆盖默认的window.confirm 展示界面，避免 title里显示为“ ：来自file:////”
         */
        public boolean onJsConfirm(WebView view, String url, String message,
                                   final JsResult result) {
            return super.onJsConfirm(view, url, message, result);
        }
    }
}
